from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis, Generation
import os
import queue
import threading
import time
import random

# 关键场景列表
scenes = [
    "艾拉刚刚擦拭好石质窗台，神秘青年凯尔出现在门口",
     "暮色中蒙面人从喷泉阴影出现",
     "艾拉持发光碎片穿越城堡迷宫般的走廊",
    "艾拉与索恩带领的皇家守卫的紧张对峙",
    "凯尔出现，艾拉与凯尔并肩战斗，对抗皇家守卫场景",
    "艾拉借用碎片光芒的力量击退守卫的高潮时刻"
     "黎明时分艾拉与凯尔骑马离开城堡"
]

task_queue = queue.Queue()
for scene in scenes:
    task_queue.put(scene)

# 全局一致性参数
STYLE_SEED = random.randint(0, 999999)
CHARACTERS = {
    "Ella": {
        "外貌": "棕褐色长发，琥珀色眼睛，面容坚毅",
        "服装": "简朴的灰褐色连衣裙，皮质围裙",
        "特征": "手持神秘发光碎片"
    },
    "Kyle": {
        "外貌": "浅金色及肩发，暴风雨灰眸，轮廓分明",
        "服装": "墨绿色天鹅绒斗篷（绣金银藤蔓星辰），皮质护甲",
        "特征": "腰间悬挂古铜罗盘"
    },
    "Thorne": {
        "外貌": "乌黑发间银丝，锐利颧骨，琥珀色发光眼",
        "服装": "黑色皮革战甲，深红色披风",
        "特征": "手持蛇形匕首"
    }
}

STYLE_PROMPT = """中世纪奇幻风格，戏剧性光影，细腻笔触，冷色调与金色点缀，8K超清"""

OPTIMIZE_SYSTEM = f"""你是专业的分镜画师，根据场景描述生成图像提示词。要求：

必须包含：
1. 角色特征：
   - 艾拉：{CHARACTERS['Ella']['外貌']}，穿着{CHARACTERS['Ella']['服装']}
   - 凯尔：{CHARACTERS['Kyle']['外貌']}，穿着{CHARACTERS['Kyle']['服装']}
   - 索恩：{CHARACTERS['Thorne']['外貌']}，穿着{CHARACTERS['Thorne']['服装']}

2. 环境要素：
   - 破败的哥特式庄园
   - 月光与人工光源交织
   - 中世纪装饰细节（铁艺、石雕、挂毯）

3. 画面要求：
   - {STYLE_PROMPT}
   - 强调材质表现（石材/金属/织物）
   - 动态构图展现戏剧冲突

直接返回优化后的提示词，不要多余内容。"""


def enhance_prompt(scene):
    """优化提示词生成"""
    try:
        response = Generation.call(
            model="qwen-max",
            system=OPTIMIZE_SYSTEM,
            messages=[{"role": "user", "content": scene}]
        )
        return response.output.choices[0].message.content if response.status_code == HTTPStatus.OK else scene
    except:
        return scene


def generate_image(final_prompt, index):
    """图像生成与保存"""
    try:
        task = ImageSynthesis.async_call(
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            model="wanx2.1-t2i-plus",
            prompt=f"{final_prompt}，{STYLE_PROMPT}",
            n=1,
            size='1024*1024',
            parameters={
                'seed': STYLE_SEED,
                'style': 'fantasy illustration',
                'quality': 'hd',
                'color_palette': 'moonlight silver,deep emerald,gold accents'
            }
        )

        rsp = ImageSynthesis.wait(task)
        if rsp.status_code == HTTPStatus.OK:
            save_image(rsp.output.results[0].url, index)
            return True
        return False
    except Exception as e:
        print(f"生成失败: {str(e)}")
        return False


def save_image(url, index):
    """保存图片并编号"""
    file_name = f"Scene_{index + 1}_{STYLE_SEED}.png"
    with open(file_name, 'wb') as f:
        f.write(requests.get(url).content)
    print(f"已保存: {file_name}")


def worker():
    """工作线程"""
    while not task_queue.empty():
        scene = task_queue.get()
        try:
            optimized = enhance_prompt(scene)
            generate_image(optimized, scenes.index(scene))
        finally:
            task_queue.task_done()


def generate_storyboard():
    """主生成流程"""
    print(f"🎬 开始生成故事板 | 风格种子: {STYLE_SEED}")
    print("角色设定:")
    for name, desc in CHARACTERS.items():
        print(f"  {name}: {desc['外貌']}，穿着{desc['服装']}")

    threads = []
    for _ in range(2):  # 控制并发数
        t = threading.Thread(target=worker)
        t.start()
        threads.append(t)

    for t in threads:
        t.join()


if __name__ == '__main__':
    start = time.time()
    generate_storyboard()
    print(f"✅ 完成! 耗时: {time.time() - start:.1f}s")